package com.asia5b.a5mall.goods.activity

import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.webkit.WebSettings
import android.webkit.WebSettings.LayoutAlgorithm
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.fragment.GoodsCouponDF
import com.asia5b.a5mall.goods.R
import com.asia5b.a5mall.goods.adapter.GoodsDetailInfoAdapter
import com.asia5b.a5mall.goods.databinding.ActivityGoodsdetail2Binding
import com.asia5b.a5mall.goods.dialog.GoodsSpecDF
import com.asia5b.a5mall.goods.fragment.GoodsCommentFragment
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.A5BMallConfigCenter
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.event.CollectGoodsChange
import com.asia5b.a5mall.middleware.logic.viewmodel.goods.GoodsDetail2ActivityVM
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.bean.GoodsDetailItemEntityIml
import com.asia5b.a5mall.middleware.model.bean.JsCall
import com.asia5b.a5mall.middleware.model.bean.ShareBean
import com.asia5b.a5mall.middleware.model.bean.ShopMenuBean
import com.asia5b.a5mall.middleware.model.goods.Goods2SkuModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.MenuPopWindow
import com.bumptech.glide.Glide
import com.google.android.material.tabs.TabLayout
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_goodsdetail2.*

/**
 * Created by zhangyuncai on 2019/12/24.
 * 商品详情
 */
@Route(path = ActCons.GoodsDetailActivity)
class GoodsDetail2Activity : SimpleActivity<GoodsDetail2ActivityVM, ActivityGoodsdetail2Binding>() {
    override val viewModelClazz: Class<GoodsDetail2ActivityVM>
        get() = GoodsDetail2ActivityVM::class.java

    override fun getDataBinding(): ActivityGoodsdetail2Binding {
        goodsId = intent.getIntExtra("goodsId", 0)
        return ActivityGoodsdetail2Binding.inflate(layoutInflater)
    }

    override var sIsDark = true
    private var goods: AbsGoodsModel? = null

    //商品sku属性
//    var skuList = ArrayList<Goods2SkuModel>()
    private var goodsId: Int = 0
    private val titles by lazy {
        arrayListOf(
                getString(R.string.商品),
                getString(R.string.评价),
                getString(R.string.详情)
        )
    }
    private val shareButton by lazy { iv_goodsdetail_share }
    private val collectButton by lazy { iv_goodsdetail_collect }
    private val moreButton by lazy { iv_goodsdetail_more }
    private val collect2Button by lazy { tv_goodsdetail_collect2 }
    private val topVessel by lazy { ll_goodsdetail_top_vessel }
    private var isScrollTop = true//是否滑到了顶部

    private val mRecyclerView by lazy { rv_goodsdetail2 }
    private val mDatas = arrayListOf<GoodsDetailItemEntityIml>()
    private val mAdapter by lazy {
        GoodsDetailInfoAdapter(this, mDatas)
    }
    private val linearLayoutManager by lazy { LinearLayoutManager(mActivity) }
    private val tab: TabLayout by lazy { tab_goodsdetail2 }

    private val webView: WebView by lazy { web_goodsdetail }

   private var pinglunHeight = 0
   private var pinglunIndex = 0
   private var xiangqingHeight = 0
   private var thrumBitmap: Bitmap? = null
        get() {
            if (field == null) {
                field = goods?.run {
                    Glide.with(mActivity)
                            .asBitmap()
                            .load(this.absGoodsImageUrl)
                            .submit()
                            .get()
                }
            }
            return field
        }


    override fun initView() {

        mRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
        }
        for (index in titles.indices) {
            val newTab = tab.newTab()
            newTab.text = titles[index]
            tab.addTab(newTab)
        }
        tab.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                when (p0?.position) {
                    0 -> {
                        nsv_goodsdetail.smoothScrollTo(0, 0)
                    }
                    1 -> {
                        nsv_goodsdetail.smoothScrollTo(0, pinglunHeight)
                    }
                    else -> {
                        nsv_goodsdetail.smoothScrollTo(0, xiangqingHeight)
                    }
                }
            }

        })


    }


    private fun setCollectStateView() {
        collect2Button.isSelected = goods!!.absGoodsCollect
        collect2Button.text = goods!!.absGoodsCollect.judge(getString(R.string.已关注), getString(R.string.关注))
        val collectRes: Int
        if (isScrollTop) {
            collectRes = if (goods!!.absGoodsCollect) {
                R.drawable.ic_collect_circleblack_press
            } else {
                R.drawable.ic_collect_circleblack_normal
            }
            topVessel.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.transparency))
            iv_goodsdetail_back.setImageResource(R.drawable.ic_goods_back_circleblack)
            shareButton.setImageResource(R.drawable.ic_goods_share_circlebalck)
            moreButton.setImageResource(R.drawable.ic_goods_more_normal)
        } else {
            collectRes = if (goods!!.absGoodsCollect) {
                R.drawable.ic_collect_press
            } else {
                R.drawable.ic_collect_normal
            }
            topVessel.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.white))
            iv_goodsdetail_back.setImageResource(R.drawable.ic_back2_black)
            shareButton.setImageResource(R.drawable.ic_goods_share_black)
            moreButton.setImageResource(R.drawable.ic_more_black)
        }
        collectButton.setImageResource(collectRes)
    }

    private fun setIntroduceItemView() {
        dddLog("setIntroduceItemView")
        var intro: String = goods!!.absGoodsShopIntro
//        var params = goods!!.param_list ?: arrayListOf()
        val localWebSettings = webView.getSettings()
        localWebSettings.useWideViewPort = true
        localWebSettings.loadWithOverviewMode = true
        localWebSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
        localWebSettings.javaScriptEnabled = true
        localWebSettings.setSupportZoom(true)
        localWebSettings.builtInZoomControls = true
        webView.isVerticalScrollBarEnabled = false
        webView.isHorizontalScrollBarEnabled = false
        webView.loadData(HtmlUtils.get.fitImageSize(intro), "text/html; charset=UTF-8", null);

        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String?) {
                view.getSettings().javaScriptEnabled = true;
                super.onPageFinished(view, url)
                addImageClickListener(view);//待网页加载完全后设置图片点击的监听方法
            }

            override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
                view.getSettings().javaScriptEnabled = true;
                super.onPageStarted(view, url, favicon)
            }

            private fun addImageClickListener(webView: WebView) {
                //通过js代码找到标签为img的代码块，设置点击的监听方法与本地的openImage方法进行连接
                val js = """
                    javascript:(function(){
                    var objs = document.getElementsByTagName("img"); 
                    for(var i=0;i<objs.length;i++)  
                    {
                        objs[i].onclick=function()  
                            {
                            window.Android.HtmlcallJava2(this.src);
                            }
                    }
                    })()
                    
                """.trimIndent()
                webView.loadUrl(js)
            }
        }
        val jsCall1 = object : JsCall() {
            override fun callbackParam(param: String) {
                val imgList = arrayListOf(param)
                ImageWatchHelper.show(context = mActivity,anyList = imgList,position = 0)
            }

        }
        webView.addJavascriptInterface(jsCall1, JsCall.H5_JSCALL_NAME)
    }


    private val shareOnClickListener = View.OnClickListener {
        if (UserRepository.isLogin(mActivity)) {
            mViewModel.collectGoods(goodsId, !(goods!!.absGoodsCollect))
        }
    }
    private val menuView by lazy {
        MenuPopWindow.build(this, ArrayList<ShopMenuBean>().then { self ->
            self.add(ShopMenuBean("首页", R.drawable.ic_goods_home, 1))
//            if (JavaShopConfigCenter.INSTANCE.DISTRIBUTION_MODE){
//                self.add(MenuVo("分销",R.drawable.javashop_icon_share_white,2))
//            }
            self.add(ShopMenuBean("店铺", R.drawable.ic_goods_shop, 3))
        }).setItemCallBack { menuVo ->
            when (menuVo.menuId) {
                1 -> {
                    push(ActCons.MainActivity)
                }
                2 -> {

                }
                3 -> {
                    push(ActCons.ShopActivity, {
                        it.withInt("shopId", goods!!.absGoodsShopId)
                    })
                }
            }
        }
    }

    override fun initEvent() {
        if (goods != null) {

            //收藏
            collectButton.setOnClickListener(shareOnClickListener)
            //更多
            moreButton.setOnClickListener {
                menuView.show(it)
            }
            ll_goodsdetail_aixin.setOnClickListener(shareOnClickListener)
            //购物车
            ll_goodsdetail_cart.setOnClickListener {
                if (UserRepository.isLogin(mActivity)) {
                    push(ActCons.CartActivity)
                }
            }
            //店铺
            ll_goodsdetail_shop.setOnClickListener {
                startShopActivity(mActivity, goods!!.absGoodsShopId)
            }
            //加入购物车
            tv_goodsdetail_addcart.setOnClickListener {
                if (UserRepository.isLogin(mActivity)) {
                    specShow()
                }
            }
            //分享
            shareButton.setOnClickListener {
                Observable.just(1)
                        .map {
                            if (thrumBitmap != null) {
                                return@map thrumBitmap!!
                            }
                            return@map 1
                        }
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe {
                            if (it is Bitmap) {
                                val shareBean = ShareBean().run {
                                    this.shareUrl = A5BMallConfigCenter.INSTANCE.WAP_GOODS_URL + "${goodsId}"
                                    this.shareImage = it
                                    this.shareTitle = goods!!.absGoodsName
                                    this.description = getString(R.string.商品_武时亿网上商城)
                                    this
                                }
                                dddLog("分享信息:${shareBean}")
                                mViewModel.shareGoods(this, shareBean)

                            }
                        }
            }
            //立即购买
            tv_goodsdetail_buynow.setOnClickListener {
                if (UserRepository.isLogin(mActivity)) {
                    buyNow()
                }
            }
        }

        nsv_goodsdetail.setOnScrollChangeListener { _: NestedScrollView?, _: Int, t: Int, _: Int, _: Int ->
            //本来的背景色:#00A7FA
            var alpha = t / 2
            if (alpha < 0) {
                alpha = 0
            } else if (alpha > 255) {
                alpha = 255
            }
            if ((isScrollTop && alpha > 150) || (!isScrollTop && alpha <= 150)) {
                isScrollTop = alpha <= 150
                setCollectStateView()
            }
            val bgColor = Color.argb(alpha, 255, 255, 255)
            ll_goodsdetail_top_vessel.setBackgroundColor(bgColor)
            tab.visibility = (alpha > 0).judge(View.VISIBLE, View.GONE)

            dddLog("t$t")
            when {
                t >= xiangqingHeight -> {
                    tab.setScrollPosition(2, 0f, true)
                }
                t >= pinglunHeight -> {
                    tab.setScrollPosition(1, 0f, true)
                }
                else -> {
                    tab.setScrollPosition(0, 0f, true)
                }
            }

        }
        ll_goodsdetail_top_vessel.setOnClickListener {
            //防止点击穿透
        }
        mAdapter.setOnItemClickListener{ _, _, position ->
            val goodsDetailItemEntityIml = mAdapter.getItem(position)
            when (goodsDetailItemEntityIml.type) {
                GoodsDetailItemEntityIml.GoodsDetail_Comments -> {
                    toComment()
                }
                GoodsDetailItemEntityIml.GoodsDetail_Shop -> {
                    startShopActivity(mActivity, goods!!.absGoodsShopId)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Coupon -> {
                    val goodsCouponDF = GoodsCouponDF().then {
                        it.mDatas.addAll(goods!!.couponList!!)
                        it.type = 1
                    }
                    goodsCouponDF.show(supportFragmentManager, "GoodsCouponDF")
                }
                GoodsDetailItemEntityIml.GoodsDetail_Activity -> {
                    val goodsCouponDF = GoodsCouponDF().then {
                        it.mDatas.addAll(goods!!.promotionList!!)
                        it.type = 2
                    }
                    goodsCouponDF.show(supportFragmentManager, "GoodsCouponDF")
                }
                GoodsDetailItemEntityIml.GoodsDetail_Spec -> {
                    specShow()
                }
            }
        }
    }

    override fun initData() {
        mViewModel.loadData(goodsId)
    }


    private fun collect(collect: Boolean) {
        goods!!.absGoodsCollect = collect
        setCollectStateView()
        getEventBus().post(CollectGoodsChange())
    }

    var listener: ViewTreeObserver.OnGlobalLayoutListener? = null

   override fun startObserver() {
        mViewModel.loadDataLiveData.observe(this, Observer { array ->
            loadDataResult(array[0] as AbsGoodsModel, array[1] as ArrayList<Goods2SkuModel>, array[2] as ResultModel<*>)
        })
        mViewModel.collectGoodsLiveData.observe(this, Observer {
            collect(it)
        })
    }

    private fun loadDataResult(goods2Model: AbsGoodsModel, goods2SkuModelList: ArrayList<Goods2SkuModel>, commentResultModel: ResultModel<*>) {
        if (goods2Model.absGoodsOff == 0) {
            showMessage(getString(R.string.该商品已下架))
            return
        }
        this.goods = goods2Model
//        skuList.clear()
//        skuList.addAll(goods2SkuModelList)


        val list = arrayListOf<GoodsDetailItemEntityIml>()
        //todo 轮播图
        list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Gallery, goods2Model.absGoodsGalleyList))
        /* todo 商品详情*/
        list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Goods, goods2Model))
        goods?.couponList?.getOrNull(0)?.run {
            //todo 优惠券
            list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Coupon, this))
        }
        goods?.promotionList?.getOrNull(0)?.run {
            //todo 活动页面
            list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Activity, this))
        }
        //todo 商品选中规格
        list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Spec, Goods2SkuModel()))
        /*todo 评论*/
        pinglunIndex = list.size
        list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Comments, arrayOf(goods, commentResultModel)))
        /*todo 店铺详情*/
        list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Shop, goods2Model.shopModel))
        /*todo 商品图片详情*/
//        list.add(GoodsDetailItemEntityIml(GoodsDetailItemEntityIml.GoodsDetail_Introduce,goods2Model))
        mDatas.clear()
        mDatas.addAll(list)
        mAdapter.notifyDataSetChanged()

        setCollectStateView()
        setIntroduceItemView()
        initEvent()

        listener = ViewTreeObserver.OnGlobalLayoutListener {
            for (index in 0 until mRecyclerView.childCount) {
                if (index <= pinglunIndex) {
                    pinglunHeight += mRecyclerView.getChildAt(index).height
                }
            }
            xiangqingHeight = mRecyclerView.height
            xiangqingHeight -= (DisplayUtils.getScreenHeight(mActivity) / 2).toInt()
            pinglunHeight -= (DisplayUtils.getScreenHeight(mActivity) / 2).toInt()
            dddLog("xiangqingHeight$xiangqingHeight")
            dddLog("pinglunHeight$pinglunHeight")
            mRecyclerView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
        mRecyclerView.viewTreeObserver.addOnGlobalLayoutListener(listener)
    }

    /**
     * 加入购物车
     */
    private fun specShow() {
        showGoodsSpecDF(true)
    }

    /**
     * 立即购买
     */
    private fun buyNow() {
//        mViewModel.buyNum(specDialog.getSelectSku().skuId, currentNum, promotionId)
        showGoodsSpecDF(false)
    }

    /**
     * 显示商品规格
     */
    private fun showGoodsSpecDF(isAddCart: Boolean) {
        if (goods == null) {
            showMessage(getString(R.string.加载中))
        } else {
            val bundel = Bundle()
            bundel.putBoolean("type", isAddCart)
            bundel.putSerializable("data", goods!!)
            bundel.putInt("goodsId", goods!!.absGoodsId)
            for (index in 0 until mDatas.size) {
                if (mDatas.get(index).type == GoodsDetailItemEntityIml.GoodsDetail_Spec) {
                    val t = mDatas.get(index).t
                    if (t != null && t is Goods2SkuModel) {
                        if (t.sku_id > 0) {
                            bundel.putSerializable("selectGoods2SkuModel", t)
                        }
                    }
                    break
                }
            }
            val dialog = sNewStanceFragment(mActivity, GoodsSpecDF::class.java, bundel)
            dialog.show(supportFragmentManager, "GoodsSpecDF")
            if (isAddCart) {
                dialog.setSureClick<Goods2SkuModel> {
                    for (index in 0 until mDatas.size) {
                        if (mDatas.get(index).type == GoodsDetailItemEntityIml.GoodsDetail_Spec) {
                            mDatas.get(index).t = it
                            mAdapter.notifyItemChanged(index)
                            break
                        }
                    }
                }
            }
        }

    }

    /**
     * 切换到评论详情
     */
    private fun toComment() {
//        val goodsCommentDF = GoodsCommentDF().then {
//            it.goodsId = goodsId
//        }
//        goodsCommentDF.show(supportFragmentManager, "GoodsCommentDF")
        ll_goodsdetail_commens.visibility = View.VISIBLE
        val animation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 1f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f)
        animation.duration = 200
        ll_goodsdetail_commens.startAnimation(animation)
        if (goodsId > 0) {
            val goodsCommentFragment = GoodsCommentFragment().then {
                it.goodsId = goodsId
                it.goods = goods
            }
            supportFragmentManager.beginTransaction()
                    .replace(R.id.fl_goodsdetail_commens, goodsCommentFragment)
                    .commit()
        }
    }

    /**
     * 隐藏评论
     */
    private fun goneComment() {
        val animation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f)
        animation.duration = 200
        ll_goodsdetail_commens.startAnimation(animation)
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                ll_goodsdetail_commens.visibility = View.GONE
            }

            override fun onAnimationStart(animation: Animation?) {
            }

        })
    }

    override fun backClick(v: View) {
        if (ll_goodsdetail_commens.visibility == View.VISIBLE) {
            goneComment()
            return
        }
        super.backClick(v)
    }

    override fun onBackPressed() {
        if (ll_goodsdetail_commens.visibility == View.VISIBLE) {
            goneComment()
        } else {
            super.onBackPressed()
        }
    }

}